<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a><cite>运营工具</cite></a>
    <a><cite>批量购买</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layadmin-search">
      <form class="layui-form" method="post" lay-filter="form_locked_orders_search">
        <script type="text/html" template>
          <div class="layui-inline">
            <div class="layui-form-label">按锁单人搜索</div>
            <div class="layui-input-inline">
              <input type="text" name="locker_mobile"
                     value="{{decodeURIComponent(layui.router().search.locker_mobile || '')}}"
                     class="layui-input" placeholder="请输入锁单人手机号">
            </div>
          </div>

          <div class="layui-inline">
            <div class="layui-form-label">价格区间</div>
            <div class="layui-inline">
              <div class="layui-input-inline">
                <input type="text" name="min_price" autocomplete="off" id="min_price" class="layui-input"
                       style="width: 100px" value="{{layui.router().search.min_price || ''}}" placeholder="最低价格">
              </div>
              <div class="layui-input-inline">~</div>
              <div class="layui-input-inline">
                <input type="text" name="max_price" autocomplete="off" id="max_price" class="layui-input"
                       style="width: 100px" value="{{layui.router().search.max_price || ''}}" placeholder="最高价格">
              </div>
            </div>
          </div>
          <div class="layui-inline layui-btn-group">
            <button type="submit" lay-submit class="layui-btn" lay-filter="submit_locked_orders_search">
              <i class="layui-icon layui-icon-search"></i>查询
            </button>
            <button type="submit" lay-submit class="layui-btn layui-btn-warm"
                    lay-filter="reset_locked_orders_search">
              <i class="layui-icon layui-icon-close"></i>重置
            </button>
            <button type="submit" lay-submit class="layui-btn layui-btn-danger"
                    lay-filter="btn_batch_unlock">
              <i class="layui-icon layui-icon-password"></i>批量解锁
            </button>
            <button type="submit" lay-submit class="layui-btn layui-btn-danger"
                    lay-filter="btn_merge_pay">
              <i class="layui-icon layui-icon-rmb"></i>合并付款
            </button>
          </div>
        </script>
      </form>
    </div>
    <div class="layui-card-body">
      <div id="table_locked_orders" lay-filter="table_locked_orders"></div>
      <script type="text/html" id="tpl_resale_user">
        {{# let resale_user = d.product.resale_user}}
        {{resale_user.auth ?  resale_user.auth.real_name: '未实名'}} ({{resale_user.mobile}})
      </script>
      <script type="text/html" id="tpl_lock_user">
        {{d.user.mobile}}
      </script>
      <script type="text/html" id="tpl_product_name">
        {{d.product.name}}
      </script>
      <script type="text/html" id="tpl_status">
        {{# let status = d.order_status.value }}
        {{# if (status === 'not_pay') { }}
        <div class="layui-table-link">
          未支付
        </div>
        {{# } else if (status === 'merge_paying') { }}
        <a class="layui-table-link layui-font-red" lay-event="cancel_merge_pay">
          合并支付中
        </a>
        {{# } }}
      </script>
    </div>
  </div>
</div>

<div id="qrcode_container" style="padding: 20px"></div>
<script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script>
  layui.use([], function () {
    let $ = layui.$
      , form = layui.form
      , table = layui.table
      , admin = layui.admin

    let resourceUrl = 'agent-admin/business/locked_orders'
      , currentPageIds = []
      , selectedIds = []

    // 列表查询
    table.render({
      elem: '#table_locked_orders'
      , url: resourceUrl
      , page: true
      , cols: [[
        {checkbox: true}
        , {title: 'ID', field: 'id', width: 80, align: "center", sort: true}
        , {title: '转售人', templet: '#tpl_resale_user', width: 180}
        , {title: '锁单人', templet: '#tpl_lock_user', width: 120}
        , {title: '商品名称', templet: '#tpl_product_name', minWidth: 100}
        , {title: '价格', field: 'display_sale_price', width: 100, align: "center"}
        , {title: '锁单时间', field: 'created_at', width: 180, align: "center"}
        , {title: '解锁时间', field: 'manual_lock_until', width: 180, align: "center"}
        , {title: '状态', templet: '#tpl_status', width: 180, align: "center"}
      ]]
      , done: function (res, curr, count) {
        // 获取当前页的数据
        var currentData = table.cache['table_locked_orders'];
        // 遍历数据，根据本地存储的选中信息设置复选框的选中状态
        currentPageIds = []
        currentData.forEach(function (item) {
          currentPageIds.push(item.id)
          var checkboxElem = $('#table_locked_orders').next().find("tr[data-index='" + item.LAY_TABLE_INDEX + "']").find(".layui-form-checkbox");
          if (selectedIds.includes(item.id)) {
            checkboxElem.addClass("layui-form-checked");
          } else {
            checkboxElem.removeClass("layui-form-checked");
          }
        });
      }
    });

    table.on('tool(table_locked_orders)', function (obj) {
      let event = obj.event
        , data = obj.data
      if (event === 'cancel_merge_pay') {
        layer.confirm('将取消该订单所属批次选中的所有订单，是否确认？', function (index) {
          admin.post("agent-admin/business/cancel_merge_pay", {order_id: data.id}, function (res) {
            layer.msg('取消订单数量: ' + res.data.cancel_order_count);
            table.reload('table_locked_orders');
          })
          layer.close(index)
        })
      }
    })

    // 监听复选框的change事件
    table.on('checkbox(table_locked_orders)', function (obj) {
      var type = obj.type; // 选中类型，可选值：all(全选)、one(单选)
      var checked = obj.checked; // 是否选中
      var data = null
      if (type === 'all') {
        data = table.cache['table_locked_orders'];
        currentPageIds.forEach(id => {
          var index = selectedIds.indexOf(id);
          if (index !== -1) {
            selectedIds.splice(index, 1);
          }
        })
        if (checked) {
          // 遍历数据，判断是否符合条件
          layui.each(data, function (index, item) {
            selectedIds.push(item.id);
            if (item.order_status.value !== 'not_pay') {
              layer.msg('请不要选择支付中订单')
            }
          })
        }
      } else {
        data = obj.data; // 当前行的数据
        if (checked) {
          // 选中时将ID添加到selectedIds中
          selectedIds.push(data.id);
          if (data.order_status.value !== 'not_pay') {
            layer.msg('请不要选择支付中订单')
          }
        } else {
          // 取消选中时将ID从selectedIds中移除
          var index = selectedIds.indexOf(data.id);
          if (index !== -1) {
            selectedIds.splice(index, 1);
          }
        }
      }
    });

    //搜索
    form.on('submit(submit_locked_orders_search)', function (d) {
      table.reload('table_locked_orders', {where: d.field, page: {curr: 1}});
      return false;
    });
    //重置
    form.on('submit(reset_locked_orders_search)', function (d) {
      $("input[name='locker_mobile']").val('');
      $("input[name='min_price']").val('');
      $("input[name='max_price']").val('');
      table.reload('table_locked_orders', {where: {}, page: {curr: 1}});
      return false;
    });
    //批量解锁
    form.on('submit(btn_batch_unlock)', function (d) {
      if (selectedIds.length == 0) {
        layer.msg('请选择要取消的订单');
        return false;
      }
      admin.post("agent-admin/business/batch_unlock", {order_ids: selectedIds}, function (res) {
        layer.msg('取消订单数量: ' + res.data.cancel_order_count);
        table.reload('table_locked_orders');
      })
      return false;
    });
    //合并付款
    form.on('submit(btn_merge_pay)', function (d) {
      if (selectedIds.length == 0) {
        layer.msg('请选择要支付的订单');
        return false;
      }
      admin.post("agent-admin/business/merge_pay", {order_ids: selectedIds}, function (res) {
        // 获取二维码容器
        var qrcodeContainer = document.getElementById('qrcode_container');
        // 调用 qrcode.js 生成二维码
        var qrcode = new QRCode(qrcodeContainer, {
          text: res.data.pay_link,
          width: 256,
          height: 256,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        });
        // 使用 layui 弹出层显示二维码
        layui.layer.open({
          title: '二维码',
          type: 1,
          content: $('#qrcode_container'), // 捕获的元素
          end: function () {
            $('#qrcode_container').html("")
            table.reload('table_locked_orders');
            layer.msg('请在支付完成后刷新页面查看')
          },
          shade: false
        });
        table.reload('table_locked_orders');
        selectedIds = []
      })
      return false;
    });
  })
</script>

